package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.LoginFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class EmployeeServerImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeServer {

    @Autowired
    private IService<Employee> iService;

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

//        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
//        qw.eq(Employee::getUsername, username);
//        Employee employee = iService.getOne(qw);
        Employee employee = lambdaQuery().eq(Employee::getUsername, username).one();

        //2、处理各种异常情况（用户名不存在、账号被锁定、密码不对）
        //用户名不存在
        if (employee == null) throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        //账号被锁定
        if (employee.getStatus() == 0) throw new LoginFailedException(MessageConstant.ACCOUNT_LOCKED);
        //密码不对
        if (!employee.getPassword().equals(DigestUtils.md5Digest(password.getBytes())))
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);

        return employee;
    }
}
